/**
 * 
 */
package com.mh.web.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Set;

import javax.servlet.http.HttpSession;
import javax.validation.ConstraintViolation;
import javax.validation.Validator;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.mh.domain.Customer;
import com.mh.service.CustomerService;
import com.mh.web.utils.CustomGenericResponse;
import com.mh.web.utils.Page;

/**
 * @author jsalazar
 * 
 */
@Controller
@RequestMapping(value = "/customer")
public class CustomerController {

	@Autowired
	private CustomerService customerService;

	public CustomerService getCustomerService() {
		return customerService;
	}

	public void setCustomerService(CustomerService customerService) {
		this.customerService = customerService;
	}

	private Validator validator;

	@Autowired
	public CustomerController(Validator validator) {
		this.validator = validator;
	}

	@RequestMapping(method = RequestMethod.GET)
	public String getPage() {

		return "customers";
	}
	
	@RequestMapping(value = "/{id}", method = RequestMethod.GET)
	public Customer read(@PathVariable("id") Integer id) {
		return customerService.findCustomerByPrimaryKey(id);
	}
	
	
	
	@RequestMapping(value="/gotoInvoices", method=RequestMethod.GET)
	public String gotoInvoices(@ModelAttribute Customer customer, HttpSession session){
		Customer cst = customerService.findCustomerByPrimaryKey(customer.getId());
		session.setAttribute("customer", cst);
		return "forward:/invoices";
	}
	

	@RequestMapping(value = "/list", method = RequestMethod.GET)
	public @ResponseBody
	Page<Customer> listCustomers(
			Customer customer
			) {
		List<Customer> list = new ArrayList<Customer>(customerService.findCustomer(customer));
		Page<Customer> pg = new Page<Customer>();
		
		pg.setRows(list);
		return pg;			
	}

	@RequestMapping(value = "/delete/{id}", method = RequestMethod.PUT)
	public @ResponseBody
	CustomGenericResponse delete(@PathVariable("id") int id) {
		CustomGenericResponse resp = new CustomGenericResponse();
		try {
			Customer customer = customerService.findCustomerByPrimaryKey(id);
			customerService.deleteCustomer(customer);
			resp.setSuccess(true);
			resp.setMessage("Success");
		} catch (Exception e) {
			resp.setSuccess(true);
			resp.setMessage("Error");
		}
		return resp;

	}

	//
	@RequestMapping(value = "/{id}", method = RequestMethod.PUT)
	public @ResponseBody
	CustomGenericResponse update(@RequestBody Customer customer,
			@PathVariable("id") int id) {
		CustomGenericResponse resp = new CustomGenericResponse();
		
		customer.setModifiedBy(getUserName());
		customer.setModifiedOn(new Date());
		
		List<String> errors = validate(customer);
		
		if (!errors.isEmpty()) {
			resp.setSuccess(false);
			resp.setMessages(errors);
			return resp;
		}
		customerService.saveCustomer(customer);

		return resp;
	}

	@RequestMapping(value = "/save", method = RequestMethod.PUT)
	public @ResponseBody
	CustomGenericResponse save(@RequestBody Customer customer) {
		CustomGenericResponse resp = new CustomGenericResponse();
		customer.setCreatedOn(new Date());
		
		customer.setCreatedBy(getUserName());
		List<String> errors = validate(customer);

		if (!errors.isEmpty()) {
			resp.setSuccess(false);
			resp.setMessages(errors);
			return resp;
		}
		customerService.saveCustomer(customer);
		return resp;
	}

	private List<String> validate(Customer customer) {
		List<String> errors = new ArrayList<String>();
		Set<ConstraintViolation<Customer>> violations = validator
				.validate(customer);
		for (ConstraintViolation<Customer> violation : violations)
			errors.add(violation.getMessage());
		return errors;
	}

	private List<String> getMessages(BindingResult result) {
		List<String> errors = new ArrayList<String>();
		for (ObjectError error : result.getAllErrors()) {
			errors.add(error.getObjectName()  +  " : " +  error.getCode() + " - " + error.getDefaultMessage());
		}
		return errors;
	}
	
	public String getUserName() {
		Object obj = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
	       String userName ="";
	       if ( obj instanceof UserDetails ) {
	    	   userName= ( (UserDetails)obj ).getUsername();
	       } else {
	    	   userName = obj.toString();
	       }
	       return userName;
		
	}

}
